
#include "Wire.h"
#include "SHT2x.h"
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>
#include <PubSubClient.h>
char mqtt_server[] = "lubo1982.myqnapcloud.cn";
// const char *mqtt_server = "192.168.3.210";
const char *mqttUser = "lu";
const char *mqttPassWd = "5891381";
const int port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
int OTAPercent;
uint32_t start;
uint32_t stop;
uint8_t macAddr[6];
SHT2x sht;String Host;
#include <OneWire.h>
#include <DallasTemperature.h>
char msg[50];
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature. 
DallasTemperature sensors(&oneWire);

 void callback(char *topic, byte *payload, unsigned int length)
{
    String message, top;

    for (int i = 0; i < length; i++)
    {
        message += (char)payload[i];
    }
    Serial.printf("R:[%s] %s\n", top.c_str(), message.c_str());
    
}
void reconnect()
{
    int i = 0;
    while (!client.connected())
    {
        if (i++ > 5)
            break;
        Serial.print("Attempting MQTT connection...");
        if (client.connect(Host.c_str(), mqttUser, mqttPassWd))
        {
            Serial.println("connected");
        }
        else
        {
            Serial.print("failed, rc=");
            Serial.println(client.state());

            delay(500);
        }
    }
    subScribe();
}
// 订阅
void subScribe()
{
    client.subscribe("TEST");
}
void setup(void)
{
 
  Serial.begin(115200);
  sensors.begin();
  sht.begin();
  uint8_t stat = sht.getStatus();
  Serial.print(stat, HEX);
  Serial.println();
      WiFiManager wifiManager;
    wifiManager.setTimeout(180);
    WiFi.macAddress(macAddr);

    Host = "POT-" + macAddr[4] + macAddr[5];
    WiFi.hostname(Host.c_str());
    if (!wifiManager.autoConnect("AutoConnect-TEST"))
    {
        Serial.println("failed to connect and hit timeout");
        delay(3000);
        //	ESP.reset();
        delay(5000);
    }
    else
        Serial.println("connected...yeey :)");
    // MQTT
    client.setServer(mqtt_server, port);
    client.setCallback(callback);
    reconnect();
	
    client.setServer(mqtt_server, port);
    client.setCallback(callback);
    subScribe();
}


void loop(void)
{ 
  sensors.requestTemperatures(); 
  float tempC = sensors.getTempCByIndex(0);
sht.read();
   client.loop();
  if (!client.connected())
    {
        reconnect();
    }
   
	sprintf(msg,  "{\"ds\":%.2f,\"SHT20temp\":%.2f,\"Humi\":%.2f}",tempC,sht.getTemperature(),sht.getHumidity());
        Serial.print("T:[test/Status]");
        Serial.println(msg);
        client.publish("test/Status", msg);
  delay(1000);
}
